/* Copyright (c) 2021 OceanBase and/or its affiliates. All rights reserved.
miniob is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */

//
// Created by WangYunlai on 2022/07/01.
//

#include "sql/operator/order_by_physical_operator.h"
#include "common/log/log.h"
#include "storage/record/record.h"
#include "storage/table/table.h"

using namespace std;

OrderByPhysicalOperator::OrderByPhysicalOperator(vector<pair<unique_ptr<Expression>, bool>> &&order_by)
  : order_by_(std::move(order_by))
{
    current_emit_index_ = -1;
}

RC OrderByPhysicalOperator::open(Trx *trx)
{
  if (children_.empty()) {
    return RC::SUCCESS;
  }

  PhysicalOperator *child = children_[0].get();
  RC                rc    = child->open(trx);
  if (rc != RC::SUCCESS) {
    LOG_WARN("failed to open child operator: %s", strrc(rc));
    return rc;
  }
  while(OB_SUCC(child->next())) {
    Tuple* tuple = child->current_tuple();
    ValueListTuple value_list_tuple;
    ValueListTuple::make(*tuple,value_list_tuple);
    tuples_.emplace_back(std::make_unique<ValueListTuple>(value_list_tuple));
  }

  sort(tuples_.begin(), tuples_.end(),
       [this](const unique_ptr<ValueListTuple> &a, const unique_ptr<ValueListTuple> &b) {
         for (const auto &order : order_by_) {
           Value a_value, b_value;
           RC rc = order.first->get_value(*a, a_value);
           if (OB_FAIL(rc)) {
             LOG_WARN("failed to find cell in tuple: %s", strrc(rc));
             ASSERT(false,"failed to find cell in tuple while sorting in order_by");
           }
           rc = order.first->get_value(*b, b_value);
           if (OB_FAIL(rc)) {
             LOG_WARN("failed to find cell in tuple: %s", strrc(rc));
             ASSERT(false,"failed to find cell in tuple while sorting in order_by");
           }
           int cmp_result = a_value.compare(b_value);
           if (cmp_result != 0) {
             return order.second ? cmp_result < 0 : cmp_result > 0;
           }
         }
         return false; // equal case
       });

  return RC::SUCCESS;
}

RC OrderByPhysicalOperator::next()
{
  current_emit_index_++;
  if (current_emit_index_ < tuples_.size()) {
    return RC::SUCCESS;
  }
  return RC::RECORD_EOF;
}

RC OrderByPhysicalOperator::close()
{
  if (!children_.empty()) {
    children_[0]->close();
  }
  //tuples_.clear();
  current_emit_index_ = -1;
  return RC::SUCCESS;
}
Tuple *OrderByPhysicalOperator::current_tuple()
{
  if (current_emit_index_ < tuples_.size()) {
    return tuples_[current_emit_index_].get();
  }
  return nullptr;
}

